package client;

/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 * Client.java
 *
 * Steven Louie Apr. 8, 2012
 *
 */
import com.esotericsoftware.kryonet.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import server.database.DatabaseConnection;
import server.scripting.npc.NPCConversationManager;
import server.scripting.npc.NPCScriptManager;

public class ActinoClient {

    private Connection conn;
    private int accId;
    private String username;
    private String password;
    private boolean loggedIn = false;
    private int attemptedLogins = 0;
    private ActinoPlayer player;
    private Map<String, ScriptEngine> engines = new HashMap<>();
    
    public ActinoClient(Connection c) {
        conn = c;
    }
    /*
     * @return int 1 - Successful 2 - Incorrect information 3 - Already logged
     * in 4 - Too many attempts 5 - Error
     */

    public int login(String user, String pass) {
        byte loginok = 5;
        attemptedLogins++;
        if (attemptedLogins > 5) {
            // Do something here
            loginok = 4;
            return loginok;
        }
        try {
            java.sql.Connection con = DatabaseConnection.getConnection();
            PreparedStatement ps = con.prepareStatement("SELECT id, password, lastknownip FROM accounts WHERE username = ?");
            ps.setString(1, user);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                accId = rs.getInt("id");
                String passT = rs.getString("password");
                if (passT.equals(pass)) {
                    username = user;
                    password = pass;
                    if (!rs.getString("lastknownip").equals(conn.getRemoteAddressTCP().getAddress().toString())) {
                        PreparedStatement lkip = con.prepareStatement("UPDATE accounts SET lastknownip = ? WHERE id = ?");
                        String addr = conn.getRemoteAddressTCP().getAddress().toString();
                        lkip.setString(1, addr);
                        lkip.setInt(2, accId);
                        lkip.executeUpdate();
                        lkip.close();
                    }
                    updateLoginState(1);
                    loginok = 1;
                    return loginok;
                }
            } else {
                loginok = 2;
                return loginok;
            }
            rs.close();
            ps.close();
        } catch (SQLException ex) {
            Logger.getLogger(ActinoClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        return loginok;
    }

    public void disconnect() {
    }

    public void updateLoginState(int newState) {
        java.sql.Connection con = DatabaseConnection.getConnection();
        try {
            PreparedStatement logstate = con.prepareStatement("UPDATE accounts SET loggedin = ?, lastlogin = CURRENT_TIMESTAMP() WHERE id = ?");
            logstate.setInt(1, newState);
            logstate.setInt(2, accId);
            logstate.executeUpdate();
            logstate.close();
        } catch (SQLException ex) {
            Logger.getLogger(ActinoClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public Connection getConn() {
        return conn;
    }

    public ActinoPlayer getPlayer() {
        return player;
    }

    public void setPlayer(ActinoPlayer player) {
        this.player = player;
    }

    public void setScriptEngine(String name, ScriptEngine e) {
        engines.put(name, e);
    }

    public ScriptEngine getScriptEngine(String name) {
        return engines.get(name);
    }

    public void removeScriptEngine(String name) {
        engines.remove(name);
    }

    public NPCConversationManager getCM() {
        return NPCScriptManager.getInstance().getCM(this);
    }
}
